﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AtDevice;

namespace Mokkula
{
    public partial class PhonebookControl : UserControl
    {
        private string _currentFilter = "";
        private IPhoneBook _phonebookInterface;

        public PhonebookControl()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            DeviceHandler.DeviceOpened += delegate(AtDevice.AtDevice device)
            {
                _phonebookInterface = device.GetPhoneBookInterface();
                RefreshNumbers();
            };
        }

        private void searchTextBox_TextChanged(object sender, EventArgs e)
        {
            if (_phonebookInterface != null)
                RefreshNumbers();
        }

        private void RefreshNumbers()
        {
            numbersView.Items.Clear();
            foreach (PhoneBookEntry entry in _phonebookInterface.GetEntries())
            {
                ListViewItem item = new ListViewItem(new string[] { entry.Name, entry.MobileNumber });
                if (ItemMatches(item, _currentFilter))
                    numbersView.Items.Add(item);
            }
        }

        private static bool ItemMatches(ListViewItem item, string filter)
        {
            foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
            {
                if (subItem.Text.Contains(filter))
                    return true;
            }
            return false;
        }
    }
}
